<template>

  <div class="app-container">
    <!--其他入库管理查询条件-->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
        <el-form-item label="单据编号" prop="docNum">
        <el-input
          v-model="queryParams.docNum"
          placeholder="请输入单据编号模糊查询"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
          @blur="trimOnBlur"
          style="width: 250px"
        />
        </el-form-item>
        <el-form-item label="仓库" prop="wmsDictWarehouse">
            <el-select v-model="queryParams.wmsDictWarehouse" style="width: 250px" placeholder="请选择仓库" clearable size="small">
              <el-option
                v-for="dict in dict.type.wms_dict_warehouse"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="单据日期">
          <el-date-picker
            v-model="queryParams.dtRange"
            size="small"
            style="width: 250px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="保管员" prop="userNameStockIn">
          <el-select
            filterable
            v-model="queryParams.userNameStockIn"
            placeholder="请选择保管员"
            clearable
            size="small"
            style="width: 250px"
          >
            <el-option
              v-for="item in inventoryUserNameList"
              :key="item.userId"
              :label="item.nickName"
              :value="item.nickName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态" prop="oaDictConfirmStatus">
        <el-select v-model="queryParams.oaDictConfirmStatus" clearable placeholder="请选择审核状态"  style="width: 250px">
          <el-option
            v-for="dict in dict.type.oa_dict_confirm_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!--其他入库列表批量操作按钮-->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="dialog_show_stockIn('4')"
          v-hasPermi="['wms:stockIn:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="dialog_show_update"
          v-hasPermi="['wms:stockIn:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wms:stockIn:remove']"
        >
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['wms:stockIn:export']"
        >导出
        </el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>
    <!--其他入库列表-->
    <el-table v-loading="loading" stripe :data="stockInList" :highlight-current-row="true" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" fixed="left"/>
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" class="demo-table-expand">
            <el-form-item label="备注：">
              <span>{{ props.row.docNote }}</span>
            </el-form-item>
            <el-form-item label="审核人：">
              <span>{{ props.row.confirmUserName }}</span>
            </el-form-item>
            <el-form-item label="审核结果：">
              <dict-tag :options="dict.type.oa_dict_confirm_status" :value="props.row.oaDictConfirmStatus"/>
            </el-form-item>
            <el-form-item label="审核时间：">
              <span>{{ props.row.confirmDt }}</span>
            </el-form-item>
            <el-form-item label="审核意见：">
              <span>{{ props.row.confirmNote }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="单据编号" align="center" prop="docNum" width="200"/>
      <el-table-column label="单据日期" align="center" prop="docDt" width="180"/>
      <el-table-column label="物料名称" align="center" prop="itemNameStock" width="150"/>
      <el-table-column label="物料编码" align="center" prop="itemNumStock" width="180"/>
      <el-table-column label="物料规格" align="center" prop="itemSpecificationStock" width="120"/>
      <el-table-column label="计量单位" align="center" prop="wmsDictMeasuringUnitStock" width="120">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.wms_dict_measuring_unit" :value="scope.row.wmsDictMeasuringUnitStock"/>
        </template>
      </el-table-column>
      <el-table-column label="数量" align="center" prop="stockInQtyDetail" width="120"/>
      <el-table-column label="保管员" align="center" prop="userNameStockIn" width="150"/>
      <el-table-column label="仓库" align="center" prop="stockName" width="150" />
      <el-table-column label="仓位" align="center" prop="stockPosName" width="150"/>
      <el-table-column label="创建日期" align="center" prop="createTime" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="oaDictConfirmStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.oa_dict_confirm_status" :value="scope.row.oaDictConfirmStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="240">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="dialog_show_update(scope.row)"
            v-hasPermi="['wms:stockIn:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['crm:crmOrders:remove']"
            :disabled="scope.row.oaDictConfirmStatus !='editing'"
          >删除
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-success"
            @click="showDialog_confirm(scope.row)"
            v-hasPermi="['mes:process:remove']"
            :disabled="scope.row.oaDictConfirmStatus !='waiting'"> 审核
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--其他入库列表分页-->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!--引用的组件-->
    <select-user ref="component_selectUser" :roleId="queryParams.roleId" @ok="selectUser_done"/>
    <stock-in ref="component_cmpStockIn" @ok="stockIn_done"/>
    <select-item ref="component_selectItem" @ok="selectItem_done"/>
    <select-order ref="component_selectOrder" @ok="selectOrder_done"/>
    <confirm ref="component_confirm" @ok="confirm_done"/>
  </div>

</template>

<script>
  import {listStockIn, delStockIn,updInventory} from "@/api/wms/stockIn";
  import selectUser from "../../system/user/selectUser";
  import stockIn from "../stockIn/cmpStockIn";
  import selectItem from "../wmsItems/selectItem";
  import {listUser} from "@/api/system/user";
  import {listRequestDetail} from "@/api/pms/requestDetails";
  import selectOrder from "../../crm/crmOrders/selectOrder";
  import { trimOnBlur } from '@/utils/form'
  import confirm from "../../oa/confirm";

  export default {
    name: "StockIn",
    dicts: ['wms_dict_warehouse', 'oa_dict_confirm_status', 'wms_dict_stock_in_type','wms_dict_measuring_unit'],
    components: {stockIn, selectUser, selectItem, confirm, selectOrder},
    data() {
      return {
        fold_form_order: 'false',
        oaDictConfirmStatus: '',
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 子表选中数据
        checkedWmsStockInDetails: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        inventoryUserNameList: [],
        orderUnitOptions: [],
        // 总条数
        total: 0,
        // 入库管理表格数据
        stockInList: [],
        // 入库单明细表格数据
        wmsStockInDetailsList: [],
        list: [],
        docTitle: null,
        docNum: null,
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          wmsDictWarehouse: null,
          fkAttentionUserId: null,
          docNum: null,
          docDt: null,
          userNameStockIn: null,
          fkPmsRequestUuid: null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          docNum: [
            {required: true, message: "请输入入库单号", trigger: "change"}
          ],
          docDt: [
            {required: true, message: "请选择入库时间", trigger: "change"}
          ],
          wmsDictWarehouse: [
            {required: true, message: "请选择仓库", trigger: "change"}
          ],
          fkAttentionUserId: [
            {required: true, message: "请选择保管员", trigger: "change"}
          ],
        },
        columns: [
          {key: 0, label: `申请日期`, visible: true},
          {key: 1, label: `申请人`, visible: true},
          {key: 2, label: `订单编号`, visible: true},
          {key: 4, label: `入库单号`, visible: true},
          {key: 5, label: `入库日期`, visible: true},
          {key: 6, label: `保管员`, visible: true},
          {key: 7, label: `仓库`, visible: true},
          {key: 8, label: `审核状态`, visible: true},
        ],
      };
    },
    created() {
      this.getList();
      this.getList_inventoryUserName();
      /**获取计量单位字典数据*/
      this.getDicts("wms_dict_measuring_unit").then(response => {
        this.orderUnitOptions = response.data;
      });
    },
    methods: {
      trimOnBlur,
      /** 打开对话框：审核 */
      showDialog_confirm(row) {
        console.log(row)
        this.confirmPassed=row
        let obj = {
          tableName: 'wms_stock_in',
          uuidColumn: 'stock_in_uuid',
          fkUuid: row.stockInUuid,
          attentionUserNickName: row.userNameStockIn,
          msg: `请审核入库管理申请, 入库单号：${row.docNum}`
        }
        this.$refs.component_confirm.showDialog_confirm(obj);

      },

      getList_inventoryUserName() {
        listUser().then(response => {
          this.inventoryUserNameList = response.rows
        });
      },

      /** 查询入库管理列表 */
      getList() {
        this.loading = true;
        if (this.queryParams.dtRange) {
          this.queryParams.dtRangeBegin = this.queryParams.dtRange[0]
          this.queryParams.dtRangeEnd = this.queryParams.dtRange[1]
        } else {
          this.queryParams.dtRangeBegin = null
          this.queryParams.dtRangeEnd = null
        }
        this.queryParams.wmsDictStockInType = '4'
        listStockIn(this.queryParams).then(response => {
          this.stockInList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          stockInUuid: null,
          wmsDictWarehouse: null,
          fkAttentionUserId: null,
          userNameStockIn: null,
          fkPmsRequestUuid: null,
          wmsDictStockInType: '1',
          docDt: parseTime(Date.now(), '{y}-{m}-{d} {h}:{i}'),
          oaDictConfirmStatus: null,
          selectedOrder: null,
          docTitle: null,
          docNum: null,
          docTitleOrder: null,
          docNumOrder: null,
          docTitleRequest: null,
          docNumRequest: null
        };
        this.wmsStockInDetailsList = [];
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },

      // 多选框选中数据
      handleSelectionChange(selection) {
        console.log(selection)
        this.ids = selection.map(item => item.stockInUuid)
        this.docDts = selection.map(item => item.docDt)
        this.docNums = selection.map(item => item.docNum)
        this.single = selection.length !== 1
        this.oaDictConfirmStatus = selection.map(i=>i.oaDictConfirmStatus)
         let editing = 'editing';
          this.multiple=
            (this.oaDictConfirmStatus.indexOf(editing)>-1 && [...new Set(this.oaDictConfirmStatus)]==editing) ? false : true
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const stockInUuids = row.stockInUuid || this.ids;
        const docDts = row.docDt || this.docDts;
        const docNums = row.docNum || this.docNums;
        this.$modal.confirm('是否确认删除入库单号为"' + docNums + '",' +
          '入库日期为"' + docDts + '"的数据项？',
          "删除确认",).then(function () {
          return delStockIn(stockInUuids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        // this.download('wms/stockIn/export', {
        //   ...this.queryParams
        // }, `wms_stockIn.xlsx`)
        this.$msgbox("待实现")
      },

      /** 对话框：显示 = 采购申请 */
      dialog_show_stockIn(request) {
        console.log(request)
        this.$refs.component_cmpStockIn.wmsDictStockInType = '4'
        this.$refs.component_cmpStockIn.dialog_show_stockIn();
      },
      /** 对话框：显示 = 采购申请 */
      dialog_show_update(row) {
        console.log(row)
        this.$refs.component_cmpStockIn.stockInUuid = row.stockInUuid||this.ids
        this.$refs.component_cmpStockIn.oaDictConfirmStatus = row.oaDictConfirmStatus
        this.$refs.component_cmpStockIn.wmsDictStockInType = '4'
        this.$refs.component_cmpStockIn.dialog_show_update();
      },

      /**完成：选择采购申请*/
      selectRequest_done(request) {
        console.log(request)
        this.queryParams.fkRequestUuid = request.requestUuid;
        listRequestDetail(this.queryParams).then(response => {
          this.wmsStockInDetailsList = response.rows;
          console.log(this.wmsStockInDetailsList)
          this.total = response.total;
          this.loading = false;
        });
        this.form.fkPmsRequestUuid = request.requestUuid
        this.form.selectedRequest = `单据编号：${request.docNum}`
      },

      /** 显示对话框：选择物料 */
      dialog_show_selectItem(scope) {
        console.log(scope)
        this.requestDetails_currRowScope = scope
        this.$refs.component_selectItem.dialog_show_selectItem();
      },

      /** 完成：选择物料*/
      selectItem_done(item) {
        this.requestDetails_currRowScope.row.fkItemUuid = item.itemUuid
        this.requestDetails_currRowScope.row.selectItemName = `${item.itemName},${item.itemNum}`
      },
      /** 打开授权用户表弹窗 */
      dialog_show_selectUser() {
        this.$refs.component_selectUser.show();
      },

      /** 选择用户完成 */
      selectUser_done(user) {
        this.form.fkAttentionUserId = user.userId
        this.form.selectedUser = `保管员：${user.nickName},保管员ID：${user.userId}`

      },

      confirm_done() {
        this.getList()
        this.updInventory()
      },

      /* 更新库存 */
      updInventory(){
        const h = this.$createElement;

        this.$notify({
          title: '退料入库单号：' + this.confirmPassed.docNum,
          message: h('i', { style: 'color: teal'}, '退料入库单审批通过，库存将被更新！')
        });
        updInventory(this.confirmPassed.stockInUuid).then(response => {
          console.log(response)
        });
      },
      /** 显示对话框：选择订单 */
      dialog_show_selectOrder() {
        this.$refs.component_selectOrder.dialog_show_selectOrder();
      },


      /** 选择订单明细完成 */
      selectOrder_done(user) {
        this.form.fkOrderUuid = user.row.orderUuid;
        this.form.selectedOrder =
          `订单编号：${user.row.docNum}`;
      },
      /** 选择订单明细完成 */
      stockIn_done() {
        this.getList()
      },

    }
  };
</script>
